import time

import numpy as np


def time_since(since):
    """
    Format elapsed time string.
    """
    now = time.time()
    elapsed_time = now - since
    return time.strftime("%H:%M:%S", time.gmtime(elapsed_time))


class EarlyStopping:
    """
    val loss metric
    """

    def __init__(self, patience=5):
        """

        Args:
            patience: 连续patience次一直没有优化，执行Early Stopping
        """
        self.patience = patience
        self.counter = 0
        self.best_loss = np.Inf  # 初始化为正无穷

    def __call__(self, val_loss):
        """
        if you use other metrics where a higher value is better, e.g. accuracy,
        call this with its corresponding negative value
        """
        if val_loss < self.best_loss:
            early_stop = False
            get_better = True
            self.counter = 0
            self.best_loss = val_loss
        else:
            get_better = False
            self.counter += 1
            if self.counter >= self.patience:
                early_stop = True
            else:
                early_stop = False

        return early_stop, get_better
